package com.egao.common.module.recommendation.service.impl;


import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.manage.CommonRefService;
import com.egao.common.module.recommendation.constants.RecommendationConstants;
import com.egao.common.module.recommendation.entity.GraduateEmploymentCertification;
import com.egao.common.module.recommendation.entity.vo.GraduateEmploymentCertificationVo;
import com.egao.common.module.recommendation.entity.vo.RecommendationAuditParam;
import com.egao.common.module.recommendation.entity.vo.RecommendationListVo;
import com.egao.common.module.recommendation.mapper.GraduateEmploymentCertificationMapper;
import com.egao.common.module.recommendation.service.IGraduateEmploymentCertificationService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.mapper.StudentMapper;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.entity.College;
import com.egao.common.module.system.entity.Dict;
import com.egao.common.module.system.entity.Major;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.mapper.CollegeMapper;
import com.egao.common.module.system.mapper.MajorMapper;
import com.egao.common.module.system.mapper.UserMapper;
import com.egao.common.module.system.service.DictService;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.*;
import com.itextpdf.text.Utilities;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 服务实现类
 *
 * @author shu
 */
@Service
public class GraduateEmploymentCertificationServiceImpl extends ServiceImpl<GraduateEmploymentCertificationMapper, GraduateEmploymentCertification> implements IGraduateEmploymentCertificationService {

    private StudentMapper studentMapper;
    private UserMapper userMapper;
    private CommonRefService refService;
    private CollegeMapper collegeMapper;
    private MajorMapper majorMapper;
    private DictService dictService;

    @Value("${minio.recmdDir}")
    private String recmdDir;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${pdf.font}")
    private String pdfFont;
    @Value("${pdf.picture}")
    private String pdfPicture;

    @Autowired
    public GraduateEmploymentCertificationServiceImpl(StudentMapper studentMapper, UserMapper userMapper, CommonRefService refService, CollegeMapper collegeMapper, MajorMapper majorMapper, DictService dictService) {
        this.studentMapper = studentMapper;
        this.userMapper = userMapper;
        this.refService = refService;
        this.collegeMapper = collegeMapper;
        this.majorMapper = majorMapper;
        this.dictService = dictService;
    }

    @Override
    public PageResult<RecommendationListVo> list(PageParam<GraduateEmploymentCertification> page) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<GraduateEmploymentCertification> wrapper = new QueryWrapper<>();
        wrapper.ge(page.getPageData().get("beginDate") != null, "update_time", page.getPageData().get("beginDate"));
        wrapper.lt(page.getPageData().get("endDate") != null, "update_time", page.getPageData().get("endDate"));
        wrapper.eq(page.getPageData().get("status") != null, "status", page.getPageData().get("status"));
        wrapper.orderByAsc("update_time");
        // 学生只能查看自己的记录
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        if (student != null) {
            wrapper.eq("user_id", student.getUserId());
            return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
        }
        //教师逻辑，仅查询本院学生
        User teacher = userMapper.selectById(curUser.getUserId());
        wrapper.eq(curUser.getDegreeScope() != null && !UserConstants.DEGREE_SCOPE_ALL.equals(curUser.getDegreeScope()),
                "degree", curUser.getDegreeScope());
        wrapper.eq("college_code", teacher.getCollegeCode());
        wrapper.ne("status", RecommendationConstants.RECOMMENDATION_STATUS_INIT);
        //处理筛选条件
        if (page.getPageData().get("con") != null && StrUtil.isNotBlank((String) page.getPageData().get("con"))) {
            wrapper.and(w -> w.like("xh", page.getPageData().get("con")).or().like("xm", page.getPageData().get("con")));
        }
        return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
    }

    public List<RecommendationListVo> models2vos(List<GraduateEmploymentCertification> models) {
        LinkedList<RecommendationListVo> vos = new LinkedList<>();
        List<String> codes = new LinkedList<>();
        models.forEach(model -> {
            RecommendationListVo vo = new RecommendationListVo();
            BeanUtils.copyProperties(model, vo);
            if (StrUtil.isNotBlank(model.getCollegeCode()) && !codes.contains(model.getCollegeCode())) {
                codes.add(model.getCollegeCode());
            }
            vos.add(vo);
        });
        Map<String, College> map = refService.refCollege(codes);
        vos.forEach(vo -> {
            if (map.get(vo.getCollegeCode()) != null) {
                vo.setCollegeName(map.get(vo.getCollegeCode()).getName());
            }
        });
        return vos;
    }

    @Override
    public JsonResult read(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        GraduateEmploymentCertification model = baseMapper.selectById(id);
        if (model == null) {
            throw new ParameterException("该普通高校毕业生就业证明表已删除！");
        }

        GraduateEmploymentCertificationVo vo = new GraduateEmploymentCertificationVo();
        BeanUtils.copyProperties(model, vo);
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", model.getUserId()));
        if (student == null) {
            throw new ParameterException("学生信息异常");
        }
        vo.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, student.getXb()));
        vo.setCsrq(student.getCsrq());
        vo.setMz(dictService.cacheLabel(DictConstants.TYPE_MZ, student.getMz()));
        vo.setZzmm(dictService.cacheLabel(DictConstants.TYPE_ZZMM, student.getZzmm()));
        vo.setSyszd(dictService.cacheLabel(DictConstants.TYPE_SYSZD, student.getSyszd()));
        vo.setMobile(student.getMobile());
        vo.setEmail(student.getEmail());
        College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
        vo.setCollegeName(college.getName());
        Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
        vo.setMajorName(major.getName());
        vo.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, student.getXl()));
        vo.setCompanyNatureLabel(dictService.cacheLabel(DictConstants.COMPANY_NATURE, model.getCompanyNature()));
        vo.setCompanyIndustryLabel(dictService.cacheLabel(DictConstants.COMPANY_INDUSTRY, model.getCompanyIndustry()));
        vo.setSignGzzwlbLabel(dictService.cacheLabel(DictConstants.TYPE_SIGN_GZZWLB, model.getSignGzzwlb()));
        return JsonResult.ok().setData(vo);
    }

    @Override
    @Transactional
    public JsonResult add(GraduateEmploymentCertification model) {
        if (model == null) {
            throw new ParameterException("参数对象为空");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<GraduateEmploymentCertification> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", curUser.getUserId());
        GraduateEmploymentCertification tmp = baseMapper.selectOne(wrapper);
        model.setUserId(curUser.getUserId());
        model.setCollegeCode(curUser.getCollegeCode());
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        model.setXh(student.getXh());
        model.setXm(student.getXm());
        model.setDegree(student.getDegree());
        model.setUpdateTime(new Date());
        if(tmp == null){
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_INIT);
            model.setCreateTime(model.getUpdateTime());
            baseMapper.insert(model);
        }else {
            if(tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                    || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)){
                model.setId(tmp.getId());
                model.setCreateTime(tmp.getCreateTime());
                baseMapper.updateById(model);
            }else {
                return JsonResult.error("已有数据进入审核流程，请勿重复添加");
            }
        }
        return read(model.getId());
    }

    @Override
    public JsonResult update(GraduateEmploymentCertification model) {
        if (model == null) {
            throw new ParameterException("参数对象为空");
        }

        if (model.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }
        GraduateEmploymentCertification tmp = baseMapper.selectById(model.getId());
        if (tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return read(model.getId());
        }
        return JsonResult.error("当前审核状态不能修改");
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null) {
            throw new ParameterException("参数对象为空");
        }

        if (ids != null && ids.length > 0) {
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }

    @Override
    public JsonResult submit(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象id为空");
        }

        GraduateEmploymentCertification model = baseMapper.selectById(id);
        if (model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                || model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_SUBMIT);
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return read(model.getId());
        }
        return JsonResult.error("已提交,请勿重复提交");
    }

    @Override
    public JsonResult audit(RecommendationAuditParam param) {
        if (param == null) {
            throw new ParameterException("参数对象为空");
        }

        if (param.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }

        GraduateEmploymentCertification model = baseMapper.selectById(param.getId());
        if (!model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_SUBMIT)) {
            throw new ParameterException("当前数据状态不满足审核条件");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        model.setReviewUser(curUser.getUserId());
        model.setStatus(param.getStatus());
        model.setReviewComment(param.getComment());
        model.setReviewTime(new Date());
        if (model.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
            model.setSchoolRecommendationTime(model.getReviewTime());
        }
        baseMapper.updateById(model);
        return read(model.getId());
    }

    @Override
    public JsonResult export(Integer id, HttpServletResponse response) throws IOException {
        GraduateEmploymentCertificationVo vo = (GraduateEmploymentCertificationVo) read(id).getData();
        String url = endpoint + "/" + MinioBucket.MINIO_RECMD + "/" + RecommendationConstants.GRAD_EMPL_CERT + "/" + vo.getUserId() + ".pdf";
        String path = recmdDir + File.separator + RecommendationConstants.GRAD_EMPL_CERT + File.separator + vo.getUserId() + ".pdf";
        if (!vo.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
            return JsonResult.error("未通过审核，无法导出");
        }
        if (vo.getGenFlag().equals(RecommendationConstants.GEN_FLAG_NO)) {
            try {

                PdfWriter writer = new PdfWriter(new FileOutputStream(path));
                PdfDocument pdf = new PdfDocument(writer);
                Document document = new Document(pdf);
                addTableDocument(document, vo);
                document.close();
                writer.close();
                UpdateWrapper<GraduateEmploymentCertification> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", vo.getId()).set("gen_flag", RecommendationConstants.GEN_FLAG_YES)
                        .set("rpt_url", url);
                baseMapper.update(null, wrapper);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + RecommendationConstants.GRAD_EMPL_CERT + ".pdf");
        File file = new File(path);
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        try (OutputStream os = response.getOutputStream()) {
            os.write(fileBytes);
        }
        return JsonResult.ok(url);
    }

    @Override
    public JsonResult read() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<GraduateEmploymentCertification> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", curUser.getUserId());
        GraduateEmploymentCertification model = baseMapper.selectOne(wrapper);
        if (model == null) {
            GraduateEmploymentCertificationVo vo = new GraduateEmploymentCertificationVo();
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
            vo.setXm(student.getXm());
            vo.setXh(student.getXh());
            vo.setDegree(student.getDegree());
            vo.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, student.getXb()));
            vo.setCsrq(student.getCsrq());
            vo.setMz(dictService.cacheLabel(DictConstants.TYPE_MZ, student.getMz()));
            vo.setZzmm(dictService.cacheLabel(DictConstants.TYPE_ZZMM, student.getZzmm()));
            vo.setSyszd(dictService.cacheLabel(DictConstants.TYPE_SYSZD, student.getSyszd()));
            vo.setMobile(student.getMobile());
            vo.setEmail(student.getEmail());
            College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
            vo.setCollegeName(college.getName());
            Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
            vo.setMajorName(major.getName());
            vo.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, student.getXl()));
            return JsonResult.ok().setData(vo);
        }
        return read(model.getId());
    }


    private void addTableDocument(Document document, GraduateEmploymentCertificationVo vo) {

        try {
            String fontUrl = pdfFont + "simsun.ttc,1";
            PdfFont font = PdfFontFactory.createFont(
                    fontUrl,
                    PdfEncodings.IDENTITY_H,                 // 编码
                    PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED  // 嵌入策略
            );

            Table table = new Table(7).setFont(font);
            table.setWidth(UnitValue.createPercentValue(100));
            table.setMinHeight(UnitValue.createPercentValue(100));
            table.setTextAlignment(TextAlignment.CENTER);

            //表头
            Cell title = new Cell(1, 7).add(new Paragraph("普通高校毕业生就业证明")).setFontSize(20)
                    .setBold().setMinHeight(40).setBorder(Border.NO_BORDER).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(title);
            //学校
            Cell schoolNameCell = new Cell(1, 4).add(new Paragraph("学校名称：中南财经政法大学"))
                    .setBold().setMinHeight(20).setBorder(Border.NO_BORDER).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(schoolNameCell);

            //学号
            Cell xhCell = new Cell(1, 3).add(new Paragraph("学号：" + vo.getXh()))
                    .setBold().setMinHeight(20).setBorder(Border.NO_BORDER).setVerticalAlignment(VerticalAlignment.MIDDLE).setTextAlignment(TextAlignment.RIGHT);
            table.addCell(xhCell);

            //第一行
            Cell graduateCell = new Cell(4, 1).add(new Paragraph("毕业生填写")).setBold()
                    .setMinHeight(60).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(graduateCell);


            addCellTOTable(table, "姓名", vo.getXm(), font);
            //性别
            Cell xblael = new Cell(1, 1).add(new Paragraph("性别"))
                    .setFont(font)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(xblael);
            Cell xbvalue = new Cell(1, 2)
                    .setTextAlignment(TextAlignment.CENTER)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            Paragraph xbParagraph = getparagraph(new Paragraph(), DictConstants.TYPE_XB, vo.getXb());
            xbvalue.add(xbParagraph);
            table.addCell(xbvalue);

            //第二行
            addCellTOTable(table, "学院", vo.getCollegeName(), font);
            addCellTOTable(table, "专业", vo.getMajorName(), font);

            //学历，第三行
            Cell xlLabel = new Cell(1, 1).add(new Paragraph("学历"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(xlLabel);
            Cell xlvalue = new Cell(1, 5)
                    .setTextAlignment(TextAlignment.CENTER)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            Paragraph xlParagraph = getparagraph(new Paragraph(), DictConstants.TYPE_XL, vo.getXl());
            xlvalue.add(xlParagraph);
            table.addCell(xlvalue);

            //第四行
            String phone = vo.getMobile() != null ? vo.getMobile() : "无";
            addCellTOTable(table, "联系方式", phone, font);
            String email = vo.getEmail() != null ? vo.getEmail() : "无";
            addCellTOTable(table, "Email", email, font);

            //第五行
            Cell companyCell = new Cell(9, 1).add(new Paragraph("用人单位填写")).setBold()
                    .setMinHeight(160).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(companyCell);

            Cell companyNameLabel = new Cell(1, 1).add(new Paragraph("单位名称\n（签章）"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            String companyName = vo.getCompanyName() != null ? vo.getCompanyName() : "无";
            Cell companyNameValue = new Cell(1, 5).add(new Paragraph(companyName))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(companyNameLabel);
            table.addCell(companyNameValue);

            //第六行
            Cell companyAddressLabel = new Cell(1, 1).add(new Paragraph("单位地址"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            String companyAdress = vo.getCompanyAddress() != null ? vo.getCompanyAddress() : "无";
            Cell companyAddressValue = new Cell(1, 5).add(new Paragraph(companyAdress))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(companyAddressLabel);
            table.addCell(companyAddressValue);

            //第七行
            String companyContactPhone = vo.getCompanyContactPhone() != null ? vo.getCompanyContactPhone() : "无";
            addCellTOTable(table, "联系电话", companyContactPhone, font);
            String companyContactPerson = vo.getCompanyContactPerson() != null ? vo.getCompanyContactPerson() : "无";
            addCellTOTable(table, "联系人", companyContactPerson, font);

            //第八行
            String companyCode = vo.getCompanyCode() != null ? vo.getCompanyCode() : "无";
            addCellTOTable(table, "统一社会信用代码", companyCode, font);
            String companyEmail = vo.getCompanyEmail() != null ? vo.getCompanyEmail() : "无";
            addCellTOTable(table, "单位邮箱", companyEmail, font);

            //单位性质，第九行
            Cell companyNatureLabel = new Cell(1, 1).add(new Paragraph("单位性质"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(companyNatureLabel);
            Cell companyNatureValue = new Cell(1, 5)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            companyNatureValue.add(new Paragraph(dictService.cacheLabel(DictConstants.COMPANY_NATURE, vo.getCompanyNature())));
            table.addCell(companyNatureValue);

            //单位所在行业，第十行
            Cell companyIndustryLabel = new Cell(1, 1).add(new Paragraph("单位所在行业"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(companyIndustryLabel);
            Cell companyIndustryValue = new Cell(1, 5)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            companyIndustryValue.add(new Paragraph(dictService.cacheLabel(DictConstants.COMPANY_INDUSTRY, vo.getCompanyIndustry())));
            table.addCell(companyIndustryValue);

            //工作职位类别，第十一行
            Cell signGzzwlbLabel = new Cell(1, 1).add(new Paragraph("工作职位类别"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(signGzzwlbLabel);
            Cell signGzzwlbyValue = new Cell(1, 5)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            signGzzwlbyValue.add(new Paragraph(dictService.cacheLabel(DictConstants.TYPE_SIGN_GZZWLB, vo.getSignGzzwlb())));
            table.addCell(signGzzwlbyValue);

            //工资收入，第十二行
            Cell salaryLabel = new Cell(1, 1).add(new Paragraph("工资收入"))
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            BigDecimal salary = vo.getSalary() != null ? vo.getSalary() : BigDecimal.ZERO;
            Cell salaryValue = new Cell(1, 5).add(new Paragraph("用人单位录（聘）用毕业生工作期间，毕业生月实际工资收入" + salary + "元" +
                    "（工资收入不低于当地最低工资标准）\n")).setTextAlignment(TextAlignment.LEFT).setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(salaryLabel);
            table.addCell(salaryValue);

            //第十三行
            //到岗时间+离校后解聘期限
            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日");
            String startDate = vo.getStartDate() != null ? formatDate.format(vo.getStartDate()) : "    年  月  日";
            addCellTOTable(table, "到岗时间", startDate, font);
            String postGraduationEmploymentTerm = vo.getPostGraduationEmploymentTerm() != null ? vo.getPostGraduationEmploymentTerm().toString() : "";
            addCellTOTable(table, "离校后解聘期限", postGraduationEmploymentTerm + "个月", font);

            //第十四行
            //学校审核
            //院系审核
            Cell reviewLabel = new Cell(3, 1).add(new Paragraph("学校审核")).setBold().setMinHeight(40)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE);
            table.addCell(reviewLabel);
            String reviewComment = vo.getReviewComment() != null ? vo.getReviewComment() : "";
            Cell reviewValue = new Cell(1, 3).add(new Paragraph("院（系）审核：" + reviewComment))
                    .setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT).setVerticalAlignment(VerticalAlignment.TOP);
            table.addCell(reviewValue);

            String schoolComment = vo.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS) ? "同意！" : "请交由学院审核！";
            Cell schoolCommentValue = new Cell(1, 3).add(new Paragraph("学校毕业生就业部门审核：" + schoolComment))
                    .setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT).setVerticalAlignment(VerticalAlignment.TOP);
            table.addCell(schoolCommentValue);

            User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", vo.getReviewUser()));
            Cell reviewUserValue = new Cell(1, 3).add(new Paragraph("院（系）就业部门负责人：" + user.getName()))
                    .setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT)
                    .setVerticalAlignment(VerticalAlignment.TOP);
            table.addCell(reviewUserValue);

            Cell schoolReviewUserValue = new Cell(1, 1).add(new Paragraph("校级就业部门\n负责人：温习\n\n\n\n"))
                    .setBorder(Border.NO_BORDER).setTextAlignment(TextAlignment.LEFT)
                    .setVerticalAlignment(VerticalAlignment.TOP);
            table.addCell(schoolReviewUserValue);
            Cell schoolSealCell = new Cell(1, 2).add(new Paragraph("签章").setMarginRight(10))
                    .setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER)
                    .setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.BOTTOM);
            if (vo.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
                addSeal(schoolSealCell);
            }
            table.addCell(schoolSealCell);

            String reviewDate = "    年  月  日";
            Date reviewTime = vo.getReviewTime();
            if (reviewTime != null) {
                reviewDate = formatDate.format(reviewTime);
            }
            Cell reviewDateValue = new Cell(1, 3).add(new Paragraph(reviewDate).setMarginRight(10))
                    .setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER)
                    .setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.BOTTOM);
            table.addCell(reviewDateValue);

            String schoolRecommendationDate = "    年  月  日";
            Date schoolRecommendationTime = vo.getSchoolRecommendationTime();
            if (schoolRecommendationTime != null) {
                schoolRecommendationDate = formatDate.format(schoolRecommendationTime);
            }
            Cell schoolRecommendationDateValue = new Cell(1, 3).add(new Paragraph(schoolRecommendationDate))
                    .setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.BOTTOM);
            table.addCell(schoolRecommendationDateValue);

            document.add(table);



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void addCellTOTable(Table table, String label, String value, PdfFont font) {
        table.addCell(new Cell().add(new Paragraph(label)).setFont(font)
                .setVerticalAlignment(VerticalAlignment.MIDDLE));
        table.addCell(new Cell(1, 2).add(new Paragraph(value)).setFont(font)
                .setVerticalAlignment(VerticalAlignment.MIDDLE));
    }

    private void addSeal(Cell cell) {
        try {
            ImageData sealData = ImageDataFactory.create(pdfPicture + "careerGuidanceSeal.jpg");
            Image sealImage = new Image(sealData);

            BackgroundPosition backgroundPosition = new BackgroundPosition().setPositionX(BackgroundPosition.PositionX.CENTER).setPositionY(BackgroundPosition.PositionY.BOTTOM);
            BackgroundRepeat.BackgroundRepeatValue backgroundRepeatValue = BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT;
            BackgroundRepeat backgroundRepeat = new BackgroundRepeat(backgroundRepeatValue, backgroundRepeatValue);
            BackgroundSize backgroundSize = new BackgroundSize();
            backgroundSize.setBackgroundSizeToValues(
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35)),
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35))
            );
            // 创建 BackgroundImage（关键修正）
            BackgroundImage backgroundImage = new BackgroundImage.Builder()
                    .setImage(sealImage.getXObject())  // 传递 Image 对象
                    .setBackgroundPosition(backgroundPosition)  // 图片居中
                    .setBackgroundRepeat(backgroundRepeat)  // 不重复平铺
                    .setBackgroundSize(backgroundSize)
                    .build();
            cell.setBackgroundImage(backgroundImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Paragraph getparagraph(Paragraph checkBoxParagraph, String type, String value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.select("label");
        wrapper.eq("type", type);
        List<Dict> dicts = dictService.getBaseMapper().selectList(wrapper);
        dicts.forEach(dict -> {
            String option = dict.getLabel();
            String target = value;
            try {
                String imageName = option.equals(target) ? "checked.png" : "unchecked.png";
                ImageData imageData = ImageDataFactory.create(pdfPicture + imageName);
                Image checked = new Image(imageData);
                //向checkBoxParagraph中加入对应图片和文字
                checkBoxParagraph.add(checked).add(option + " ");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return checkBoxParagraph;
    }

}